import {ref} from 'vue'
import { findIndex } from 'lodash'
import { getHierarchyTopoData } from "@/api/topoNodeDetail";
import { Message } from "@garco-design/web-vue";

export default function useHierarchyData() {
  const hierachyTopoData = ref();
  // 获取分层拓扑数据
  const getTopoData = (params) => {
    getHierarchyTopoData(params).then((res) => {
      if (res.code === 200) {
        const { nodes, links } = res.data;
        if (Array.isArray(nodes) && !nodes.length) {
          Message.warn("返回分层拓扑数据为空");
          return;
        }
        nodes.forEach((node, index) => (node.idx = index));
        const edges = buildEdges(links, nodes);
        hierachyTopoData.value = { nodes, edges };
      }
    });
    // 分层拓扑构造调用关系
    const buildEdges = (links, nodes) => {
      const edges = [];
      links.forEach((link) => {
        const ids = link.split(",");
        if (
          findIndex(nodes, { uid: ids[0] }) > -1 &&
          findIndex(nodes, { uid: ids[1] }) > -1
        ) {
          edges.push({
            source: findIndex(nodes, { uid: ids[0] }),
            target: findIndex(nodes, { uid: ids[1] }),
          });
        }
      });
      return edges;
    };
  };
  return {
    hierachyTopoData,
    getTopoData
  }
}
